package com.shushan.mixedexam.readrecite;

import android.content.res.AssetFileDescriptor;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.iflytek.cloud.EvaluatorListener;
import com.iflytek.cloud.EvaluatorResult;
import com.iflytek.cloud.SpeechError;
import com.shushan.base.BaseFragment;
import com.shushan.mixedexam.BaseExamFragment;
import com.shushan.mixedexam.readrecite.bean.ReadReciteDataBean;
import com.shushan.shushanbao.R;
import com.shushan.ui.RoundProgressBar;
import com.shushan.util.AudioRecordUtil;
import com.shushan.util.ExamAudioPlayUtil;
import com.shushan.util.MediaRecordUtil;
import com.shushan.util.DensityUtil;
import com.shushan.util.PopupWindowUtil;
import com.shushan.util.SpeechEvaluatorUtil;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @ClassName: ReadReciteExamFragment
 * @Desciption: //阅读背诵试题fragment
 * @author: zhangshihao
 * @date: 2018-06-20
 */
public class ReadReciteExamFragment extends BaseExamFragment implements View.OnClickListener,EvaluatorListener{

    private static final String TAG = ReadReciteExamFragment.class.getSimpleName();

    private static final int CLICK_TYPE_PLAY = 1;
    private static final int CLICK_TYPE_RECORD = 2;
    private static final int CLICK_TYPE_RECORD_PLAY = 3;

    private RelativeLayout rootView;
    private LinearLayout oldControlPad;
    private View oldScorePad;
    private RelativeLayout imgContainer;
    private RoundProgressBar pbRecordPlay;
    private boolean isShowRight = true;//是否将得分显示在右边

    private int currentBtnIndex;
    private List<Integer> alreadyScoreIndexList;
    private List<HashMap<Integer,Integer>> scoreMapList;
    private List<HashMap<Integer,Button>> btnList;
    private int bgResId;
    private List<ReadReciteDataBean> rrDataBeans;
    private int vpWidth,vpHeight;
    private int imgWidth,imgHeight;
    private String recordPath = AudioRecordUtil.getInstance().getOutFileName();

    private PopupWindow coverPopup;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 0){
                ((Button) msg.obj).setBackgroundResource(R.color.alph_80_btn_blue);
            }
        }
    };

    private OnControlPadClickListener onControlPadClickListener = new OnControlPadClickListener() {
        @Override
        public void OnControlPadClick(int index,int clickType,double begin,double end,RoundProgressBar pb,String text) {
            handleClickEvent(index,clickType,begin,end,pb,text);
        }
    };

    private void handleClickEvent(int index,int clickType, final double begin, final double end, RoundProgressBar pb, final String text){
        Log.i(TAG,"handleClickEvent : clickType == "+clickType+" ; begin == "+(begin*1000)+" ; end == "+(end*1000));
        switch (clickType){
            case CLICK_TYPE_PLAY:
//                AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.langbei);
//                ExamAudioPlayUtil.playAudioSection(begin,end,pb,file);
                break;
            case CLICK_TYPE_RECORD:
                ExamAudioPlayUtil.stopPlay();
                coverPopup = PopupWindowUtil.showCoverPopupWindow(getActivity(),rootView);
                final Button btn = btnList.get(index).get(index);
                AudioRecordUtil.getInstance().startRecord();
                AudioRecordUtil.getInstance().recordData();
                pb.countBack(pb,(int) ((end-begin)*1000));
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        AudioRecordUtil.getInstance().stopRecord();
                        AudioRecordUtil.getInstance().convertWaveFile();
                        mHandler.sendMessage(mHandler.obtainMessage(0,btn));
                        SpeechEvaluatorUtil.startEva(AudioRecordUtil.getAudioData(recordPath),text,ReadReciteExamFragment.this);
                        ExamAudioPlayUtil.playAudio(pbRecordPlay, recordPath, new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                coverPopup.dismiss();
                            }
                        });
                    }
                },(long)((end-begin)*1000));
                break;
            case CLICK_TYPE_RECORD_PLAY:
                ExamAudioPlayUtil.stopPlay();
                ExamAudioPlayUtil.playAudio(pb, recordPath,null);
                break;
        }
    }

    public static ReadReciteExamFragment newInstance(int bgResId,int vpWidth,int vpHeight, List<ReadReciteDataBean> rrDataBeans){
        ReadReciteExamFragment nrrExamFragment = new ReadReciteExamFragment();
        nrrExamFragment.setBgResId(bgResId);
        nrrExamFragment.setRrDataBeans(rrDataBeans);
        nrrExamFragment.setVpWidth(vpWidth);
        nrrExamFragment.setVpHeight(vpHeight);

        return nrrExamFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SpeechEvaluatorUtil.init(getContext());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = new RelativeLayout(getContext());
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        rootView.setLayoutParams(layoutParams);

        initView();

        return rootView;
    }

    private void initView(){
        alreadyScoreIndexList = new ArrayList<>();
        scoreMapList = new ArrayList<>();
        btnList = new ArrayList<>();

        setImgSize();
        float scaleRate = getScaleRate();
        imgContainer = new RelativeLayout(getContext());
        RelativeLayout.LayoutParams containerParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        containerParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        imgContainer.setLayoutParams(containerParams);
        rootView.addView(imgContainer,containerParams);
        ImageView imageView = new ImageView(getContext());
        imageView.setImageResource(bgResId);
        final int imgDisplayWidth = (int)(imgWidth/scaleRate);
        int imgDisplayHeight = (int)(imgHeight/scaleRate);
        RelativeLayout.LayoutParams imgParams = new RelativeLayout.LayoutParams(imgDisplayWidth,imgDisplayHeight);
        imgParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        imageView.setLayoutParams(imgParams);
        imgContainer.addView(imageView,imgParams);
        for(int i=0;i<rrDataBeans.size();i++){
            final int index = i;
            final ReadReciteDataBean dataBean = rrDataBeans.get(i);

            Button btn = new Button(getActivity());
            btn.setBackgroundResource(R.color.transparent);
            final int btnWidth = (int)((float)dataBean.width/scaleRate);
            final int btnHeight = (int) ((float)dataBean.height/scaleRate);
            RelativeLayout.LayoutParams btnparams = new RelativeLayout.LayoutParams(btnWidth,btnHeight);
            final int left = (int)( dataBean.left/scaleRate);
            final int top = (int)(dataBean.top/scaleRate);
            btnparams.leftMargin = left;
            btnparams.topMargin = top;
            btn.setLayoutParams(btnparams);
            btn.setBackgroundResource(R.color.alph_80_red);

            btn.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if(oldControlPad != null){
                        oldControlPad.setVisibility(View.GONE);
                    }
                    createControlPad(index,left,top,btnHeight,imgDisplayWidth,dataBean.begin, dataBean.end,dataBean.text);
                    currentBtnIndex = index;
                }
            });
            imgContainer.addView(btn);

            HashMap<Integer,Button> map = new HashMap();
            map.put(i,btn);
            btnList.add(map);
        }
    }

    private void createControlPad(int index,int left,int top,int btnHeight,int imgDisplayWidth,double begin,double end,String text){
        oldControlPad = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.popup_control_pad,null,false);
        oldControlPad.measure(0,0);
        RelativeLayout.LayoutParams padParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        int padWidth = oldControlPad.getMeasuredWidth();
        View scorePad = LayoutInflater.from(getContext()).inflate(R.layout.score_pad,null,false);
        scorePad.measure(0,0);
        int scorePadWidth = scorePad.getMeasuredWidth();
        int scorePadHeight = scorePad.getMeasuredHeight();
        if(top - scorePadHeight >= 0){
            padParams.topMargin = top - (DensityUtil.dip2px(getContext(),36f));
        }else{
            padParams.topMargin = top + btnHeight;
        }
        int leftMove = (left + padWidth + DensityUtil.dip2px(getContext(),106f)) - imgDisplayWidth;
        isShowRight = true;
        if(left + padWidth > imgDisplayWidth) {
            padParams.leftMargin = left - ((left + padWidth)-imgDisplayWidth);
            isShowRight = false;
        }else{
            padParams.leftMargin = left;
            if((left + padWidth + DensityUtil.dip2px(getContext(),106f)) > imgDisplayWidth){
                isShowRight = false;
            }
        }
        if(!isShowRight){
            padParams.leftMargin = left - leftMove;
        }
        imgContainer.addView(oldControlPad,padParams);
        setClickEvent(index,begin,end,text);

        for(int i=0;i<alreadyScoreIndexList.size();i++){
            int alreadyScoreIndex = alreadyScoreIndexList.get(i);
            if(alreadyScoreIndex == index){
                for(int j=0;j<scoreMapList.size();j++){
                    for(int key : scoreMapList.get(j).keySet()){
                        if(key == alreadyScoreIndex){
                            HashMap map = scoreMapList.get(j);
                            addScorePad((int)map.get(key),oldControlPad);
                            return;
                        }
                    }
                }
            }
        }
    }

    private void addScorePad(int score,LinearLayout contentView){
        View scorePad = LayoutInflater.from(getContext()).inflate(R.layout.score_pad,null,false);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        Log.i(TAG,"showoldScorePad : isShowRight == "+isShowRight);
        if(isShowRight) {
            contentView.addView(scorePad,params);
        }else {
            contentView.addView(scorePad,0,params);
        }

        TextView tvScore = scorePad.findViewById(R.id.tv_score);
        ImageView ivScore = scorePad.findViewById(R.id.iv_score);
        tvScore.setText(String.valueOf(score)+"分");
        Log.i(TAG,"score == "+String.valueOf(score)+"分");
        if(score >= 70){
            ivScore.setImageResource(R.drawable.ic_high_score);
        }else{
            ivScore.setImageResource(R.drawable.ic_low_score);
        }
    }

    private void setClickEvent(final int index, final double begin, final double end, final String text){
        RelativeLayout rlTopPlay = oldControlPad.findViewById(R.id.rl_top_play);
        final RoundProgressBar pbTopPlay = oldControlPad.findViewById(R.id.pb_top_play);
        RelativeLayout rlTopRecord = oldControlPad.findViewById(R.id.rl_top_record);
        final RoundProgressBar pbTopRecord = oldControlPad.findViewById(R.id.pb_top_record);
        RelativeLayout rlTopRecordPlay = oldControlPad.findViewById(R.id.rl_top_record_play);
        final RoundProgressBar pbTopRecordPlay = oldControlPad.findViewById(R.id.pb_top_record_play);
        rlTopPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pbRecordPlay = pbTopRecordPlay;
                onControlPadClickListener.OnControlPadClick(index,CLICK_TYPE_PLAY,begin,end,pbTopPlay,text);
            }
        });
        rlTopRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pbRecordPlay = pbTopRecordPlay;
                onControlPadClickListener.OnControlPadClick(index,CLICK_TYPE_RECORD,begin,end,pbTopRecord,text);
            }
        });
        rlTopRecordPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onControlPadClickListener.OnControlPadClick(index,CLICK_TYPE_RECORD_PLAY,begin,end,pbTopRecordPlay,text);
            }
        });
    }

    private float getScaleRate(){
        float imgScale = (float)imgWidth/(float)imgHeight;
        float vpScale = (float)vpWidth/(float)vpHeight;
        float scale;
        if(imgScale > vpScale){
            scale = (float)imgWidth/(float)vpWidth;
        }else{
            scale = (float)imgHeight/(float)vpHeight;
        }
        return scale;
    }

    private void setImgSize(){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//这个参数设置为true才有效
        BitmapFactory.decodeResource(getResources(),bgResId,options);
        imgHeight=options.outHeight;
        imgWidth= options.outWidth;
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onError(SpeechError speechError) {

    }

    @Override
    public void onEvent(int i, int i1, int i2, Bundle bundle) {

    }

    @Override
    public void onVolumeChanged(int i, byte[] bytes) {

    }

    @Override
    public void onBeginOfSpeech() {

    }

    @Override
    public void onEndOfSpeech() {

    }

    @Override
    public void onResult(EvaluatorResult result, boolean isLast) {
        Log.d(TAG,"onresult : isLast == "+isLast);
        if (isLast) {
            StringBuilder builder = new StringBuilder();
            builder.append(result.getResultString());
            if(oldScorePad != null && oldScorePad.getVisibility() == View.VISIBLE){
                oldScorePad.setVisibility(View.GONE);
            }
            showScorePad(parseXml(builder.toString()));
        }
    }

    private void showScorePad(float score){
        oldScorePad = LayoutInflater.from(getContext()).inflate(R.layout.score_pad,null,false);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        Log.i(TAG,"showoldScorePad : isShowRight == "+isShowRight);
        if(isShowRight) {
            if(oldControlPad.getChildCount() == 4){
                oldControlPad.removeViewAt(3);
            }
            oldControlPad.addView(oldScorePad,params);
        }else {
            if(oldControlPad.getChildCount() == 4){
                oldControlPad.removeViewAt(0);
            }
            oldControlPad.addView(oldScorePad,0,params);
        }

        int hundredScore = (int) (score * 20);
        TextView tvScore = oldScorePad.findViewById(R.id.tv_score);
        ImageView ivScore = oldScorePad.findViewById(R.id.iv_score);
        tvScore.setText(String.valueOf(hundredScore)+"分");
        Log.i(TAG,"score == "+String.valueOf(hundredScore)+"分");
        if(hundredScore >= 70){
            ivScore.setImageResource(R.drawable.ic_high_score);
        }else{
            ivScore.setImageResource(R.drawable.ic_low_score);
        }

        HashMap<Integer,Integer> map = new HashMap<>();
        map.put(currentBtnIndex,hundredScore);
        for(int i=0;i<scoreMapList.size();i++){
            HashMap<Integer,Integer> tempMap = scoreMapList.get(i);
            for(int key : tempMap.keySet()){
                if(key == currentBtnIndex){
                    scoreMapList.remove(i);
                }
            }
        }
        scoreMapList.add(map);
        alreadyScoreIndexList.add(currentBtnIndex);
    }

    private float parseXml(String xmlStr){
        float totalScore = 0f;
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            xmlPullParser.setInput(new StringReader(xmlStr));
            int eventType = xmlPullParser.getEventType();
            String value;
            while(eventType != xmlPullParser.END_DOCUMENT) {
                String nodeName = xmlPullParser.getName();
                switch (eventType){
                    case XmlPullParser.START_TAG:
                        if("total_score".equals(nodeName)){
                            value = xmlPullParser.getAttributeValue(0);
                            totalScore = Float.parseFloat(value);
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                eventType = xmlPullParser.next();
            }
        }catch (XmlPullParserException xppe){
            Log.i(TAG,xppe.toString());
        }catch (IOException ioe){
            Log.i(TAG,ioe.toString());
        }
        return totalScore;
    }

    public void setBgResId(int bgResId) {
        this.bgResId = bgResId;
    }

    public void setRrDataBeans(List<ReadReciteDataBean> rrDataBeans) {
        this.rrDataBeans = rrDataBeans;
    }

    public void setVpWidth(int vpWidth) {
        this.vpWidth = vpWidth;
    }

    public void setVpHeight(int vpHeight) {
        this.vpHeight = vpHeight;
    }

    public void setImgWidth(int imgWidth) {
        this.imgWidth = imgWidth;
    }

    public void setImgHeight(int imgHeight) {
        this.imgHeight = imgHeight;
    }

    private interface OnControlPadClickListener{
        void OnControlPadClick(int index,int clickType,double begin,double end,RoundProgressBar pb,String text);
    }

}
